<template>
  <div style="padding: 10px;width: 100%">
    <!--头部功能区-->
    <div>
      <el-row :gutter="20">
        <el-col :span="2">
          <!-- 功能区 -->
          <el-button type="primary" @click="add">新增</el-button>
        </el-col>
        <el-col :span="2">
          <el-upload
              ref="input"
              action="/"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="importExcel"
              type="file" class="grid-content">
            <el-button type="primary">导入</el-button>
          </el-upload>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="outfile">导出</el-button>
        </el-col>
        <el-col :span="10">
          <div class="grid-content bg-purple"></div>
        </el-col>
        <el-col :span="8">
          <!-- 搜索区 -->
          <el-input v-model="search" placeholder="请输入关键字" style="width: 80%;" clearable></el-input>
          <el-button type="primary" style="margin-left:2px ;" @click="load">查询</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 表格内容 -->
    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="bookId" label="书籍编号" sortable>
      </el-table-column>
      <el-table-column prop="bookName" label="书籍名称">
      </el-table-column>
      <el-table-column prop="author" label="书籍作者">
      </el-table-column>
      <el-table-column prop="price" label="书籍价格">
      </el-table-column>
      <el-table-column prop="publish" label="出版日期">
      </el-table-column>
      <el-table-column label="书籍封面">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.cover"
              :preview-src-list="[scope.row.cover]">
          </el-image>
        </template>
      </el-table-column>
      
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button @click="handleEdit(scope.row)" type="success" size="mini">编辑</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row.bookId)">
            <template #reference>
              <el-button type="danger" size="mini">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页栏 -->
    <div style="margin: 10px 0;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-sizes="[5, 10, 20]" :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      <!-- 新增弹窗 -->
      <el-dialog title="编辑信息" v-model="dialogVisible" width="30%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="书籍名称">
            <el-input v-model="form.bookName" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="书籍作者">
            <el-input v-model="form.author" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="书籍价格">
            <el-input v-model="form.price" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="出版日期">
            <el-date-picker v-model="form.publish" value-format="YYYY-MM-DD" type="date"
                            style="width: 80%;"></el-date-picker>
          </el-form-item>
          
          <el-form-item label="书籍封面">
            <el-upload
                ref="upload"
                :on-success="uploadSuccess"
                :action="filesUpload">
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="save">确 定</el-button>
                    </span>
        </template>
      </el-dialog>
    </div>
  
  </div>
</template>

<script>

import request from "@/utils/request";
import XLSX from 'xlsx';

export default {
  name: 'Books',
  components: {},
  data() {
    return {
      form: {},
      search: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      tableData: [],
      filesUpload: "http://" + window.server.filesUpload + ":9090/files/upload/"
    }
  },
  created() {
    console.log(this.filesUpload)
    this.load()
  },
  methods: {
    // 导入数据
    importExcel(file) {
      // let file = file.files[0] // 使用传统的input方法需要加上这一步
      const types = file.name.split('.')[1]
      const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types)
      if (!fileType) {
        alert('格式错误！请重新选择')
        return
      }
      this.file2Xce(file).then(tabJson => {
        if (tabJson && tabJson.length > 0) {
          this.xlsxJson = tabJson
          console.log(this.tableData)
          const dataJson = this.xlsxJson[0].sheet
          console.log(dataJson)
          for (let i = 0; i < dataJson.length; i++) {
            this.form = dataJson[i]
            this.save()
          }
          // xlsxJson就是解析出来的json数据,数据格式如下
          // [
          //   {
          //     sheetName: sheet1
          //     sheet: sheetData
          //   }
          // ]
        }
      })
    },
    // 解析Excel文件
    file2Xce(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        reader.onload = function (e) {
          const data = e.target.result
          this.wb = XLSX.read(data, {
            type: 'binary'
          })
          const result = []
          this.wb.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            })
          })
          resolve(result)
        }
        reader.readAsBinaryString(file.raw)
        // reader.readAsBinaryString(file) // 传统input方法
      })
    },
    // 导出数据
    outfile() {
      const that = this;
      const titleArr = Object.keys(that.tableData[0]);
      let tableData = [titleArr]
      this.tableData.forEach(item => {
        let rowData = []
        titleArr.map((key, index) => {
          rowData.push(item[key])
        })
        tableData.push(rowData)
      })
      // 设置表头
      tableData[0] = ['书籍编号', '书籍名称', '数据作者', '书籍价格', '出版时间', '书籍封面url',];
      let ws = XLSX.utils.aoa_to_sheet(tableData)
      let wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '书籍表') // 工作簿名称
      XLSX.writeFile(wb, '书籍表.xlsx') // 保存的文件名
    },
    // 加载数据
    load() {
      request.get("/books", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search,
        }
      }).then(res => {
        // console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    // 新增数据
    add() {
      this.dialogVisible = true;
      this.form = {}
      if (this.$refs['upload']) {
        this.$refs['upload'].clearFiles() //清除上传文件记录
      }
    },
    // 点击保存触发
    save() {
      if (this.form.bookId) { //更新数据
        request.put("/books", this.form).then(res => {
          // console.log(res)
          this.mgs(res.codes, "更新")
          this.dialogVisible = false //关闭弹窗
        })
      } else { //新增数据
        request.post("/books", this.form).then(res => {
          // console.log(res)
          this.mgs(res.codes, "新增")
          this.dialogVisible = false //关闭弹窗
        })
      }
      this.$refs['upload'].clearFiles() //清除上传文件记录
    },
    // 数据编辑
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
      this.$nextTick(() => { //处理未来元素
        if (this.$refs['upload']) {
          this.$refs['upload'].clearFiles() //清除上传文件记录
        }
      })
    },
    //上传成功返回
    uploadSuccess(res) {
      // console.log(res)
      this.form.cover = res.data
    },
    // 数据删除
    handleDelete(bookId) {
      console.log(bookId)
      request.delete("/books/" + bookId).then(res => {
        this.mgs(res.codes, "删除")
      })
    },
    // 改变当每页个数触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    // 改变当前页码触发
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.load()
    },
    // 返回结果判定
    mgs(code, str) {
      if (code === '200') {
        this.$message({
          type: "success",
          message: str + "成功"
        })
      } else {
        this.$message({
          type: "error",
          message: str + "失败"
        })
      }
      this.load() //刷新表格
    }
  }
}
</script>
